package com.maxd.handler.pay;

import com.maxd.constants.PayScene;
import com.maxd.error.DescribeException;
import com.maxd.error.ExceptionEnum;
import com.maxd.model.ActivityJoinRecord;
import com.maxd.model.PayRecord;
import com.maxd.model.UserMemberRecord;
import com.maxd.respository.UserMemberRecordRepository;
import com.maxd.respository.activitties.ActivityJoinRecordRepository;
import com.maxd.service.activity.IRwActivityService;
import com.maxd.service.member.IMemberService;
import com.maxd.utils.AssertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MemberPayHandler implements IPayHandler {

    private static final Logger log = LoggerFactory.getLogger(MemberPayHandler.class);
    @Autowired
    private UserMemberRecordRepository userMemberRecordRepository;

    @Autowired
    private IMemberService memberService;

    @Override
    public String getScene() {
        return PayScene.MEMBER_PAY.getCode();
    }

    @Override
    public void preHandler(PayRecord payRecord) {
        // 支付金额校验
        UserMemberRecord param = new UserMemberRecord();
        param.setTransId(payRecord.getBusinessId());
        List<UserMemberRecord> records = userMemberRecordRepository.findAll(Example.of(param));
        AssertUtil.notEmpty(records, ExceptionEnum.ORDER_NOF);
        if(!"0".equals(records.get(0).getStatus()) && !"1".equals(records.get(0).getStatus())) {
            log.error("活动支付预校验状态不正确，状态为:{}", records.get(0).getStatus());
            throw new DescribeException(ExceptionEnum.PAYED_OR_CANCELED);
        }
    }

    @Override
    public void postHandler(PayRecord payRecord) {
        log.info("调用微信预支付成功，更新用户会员表的状态:{}", payRecord);
        userMemberRecordRepository.updateStatus(payRecord.getBusinessId(), "1");
    }

    @Override
    public void callBackHandler(PayRecord payRecord) {
        log.info("微信支付成功，更新用户会员表的状态:{}", payRecord);
        userMemberRecordRepository.updateStatus(payRecord.getBusinessId(), "2");
    }

    @Override
    public void cancelHandler(PayRecord payRecord) {
        memberService.cancel(payRecord.getBusinessId(), payRecord.getUserId());
    }
}
